const express = require('express')
const router = express.Router()
const models = require('../models')
const getTotal = require('../utils/get-total')
const Op = models.Sequelize.Op
const {v4: uuidv4} = require('uuid')
const {success, error} = require('../utils/message')

router.get('/', async function (req, res, next) {
    const where = {}
    const status = req.query.status

    if (status) {
        if (status == 'checked') {
            where.status = {
                [Op.eq]: 1
            }
        }

        if (status == 'paid') {
            where.status = {
                [Op.in]: [2, 3, 4]
            }
        }
    }

    const orders = await models.Order.findAll({
        order: [['id', 'DESC']],
        where: where,
        include: [
            {
                model: models.OrderProduct,
                as: 'products'
            }
        ],
    })

    success(res, '查询成功', {orders})
})

// 确认订单
router.get('/checkout', async function (req, res, next) {
    // 购物车
    const carts = await models.Cart.findAll({
        where: {userId: req.decoded.user.id},
        include: [{
            model: models.Product,
            as: 'product'
        }],
    })

    if (carts.length == 0) {
        return error(res, '您还没有添加商品到购物车！')
    }

    // 收货地址
    const user = await models.User.findByPk(req.decoded.user.id)
    if (!user.addressId) {
        return error(res, '您还没有设置收货地址！')
    }
    const address = await models.Address.findByPk(user.addressId)

    // 统计数
    const total = getTotal(carts)

    success(res, '查询成功', {address, carts, total})
})

// 生成订单
router.post('/', async function (req, res, next) {
    const addressId = req.body.addressId
    const userId = req.decoded.user.id
    if (!addressId) {
        return error(res, '请选择收货地址！')
    }

    // 查询购物车信息
    const carts = await models.Cart.findAll({
        where: {userId: userId},
        include: [{
            model: models.Product,
            as: 'product'
        }],
    })

    if (carts.length == 0) {
        return error(res, '您还没有添加商品到购物车！')
    }
    // 统计购物车的总金额、总数量
    const total = getTotal(carts)

    // 1、插入到订单表
    const order = await models.Order.create({
        outTradeNo: `healthy-${userId}-${uuidv4()}`,
        userId: userId,
        status: 1,
        totalPrice: total.price,
        totalNum: total.num
    })

    // 2、插入到订单商品表
    carts.map(async cart => {
        await models.OrderProduct.create({
            orderId: order.id,
            name: cart.product.name,
            image: cart.product.image,
            price: cart.product.price,
            num: cart.num,
        })
    })

    // 3、插入到订单地址表
    const address = await models.Address.findByPk(addressId)
    await models.OrderAddress.create({
        orderId: order.id,
        province: address.province,
        city: address.city,
        area: address.area,
        detail: address.detail,
        name: address.name,
        tel: address.tel,
    })

    // 4、清空当前用户的购物车
    await models.Cart.destroy({where: {userId: req.decoded.user.id}})

    success(res, '订单生成成功', {order})
})

// 查询当前记录
router.get('/:id', async function (req, res, next) {
    const id = req.params.id

    const order = await models.Order.findOne({
        where: {id: id},
        include: [
            {
                model: models.OrderProduct,
                as: 'products'
            },
            {
                model: models.OrderAddress,
                as: 'address'
            },
            {
                model: models.Express,
                as: 'express'
            }
        ]
    })

    if (!order) {
        return error(res, '当前订单不存在')
    }

    success(res, '查询成功', {order})
})

module.exports = router
